package cn.airfei.netty.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description:
 * @author: air
 * @create: 2020-12-30 10:11
 */
public class BIOService {
    public static void main(String[] args) throws IOException {
        // 穿件线程池
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();

        // 创建severSocket
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动了....");
        while (true){
            // 监听客户端连接
            final Socket socket=serverSocket.accept();
            System.out.println("连接一个客户端了");
            // 创建一个线程
            newCachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    handler(socket);
                }
            });
        }
    }


    public static void handler(Socket socket){
        byte[] bytes=new byte[1024];
        System.out.println("线程id:"+Thread.currentThread().getId()+",线程名称:"+Thread.currentThread().getName());
        try {
            InputStream inputStream = socket.getInputStream();
            while (true){
                System.out.println("线程id:"+Thread.currentThread().getId()+",线程名称:"+Thread.currentThread().getName());
                int read = inputStream.read(bytes);
                if (read!=-1){
                    System.out.println(new String(bytes,0,read));
                }else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭client连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
